﻿using Cyss.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using System.Threading.Tasks;

namespace Cyss.Core.Api.Client
{
    public static class ServiceCollectionExtensions
    {


        /// <summary>
        /// 注册所有Order 库api接口
        /// </summary>
        /// <param name="services"></param>
        public static void RegisterBaseClient<T>(this IServiceCollection services,Assembly assembly ,string httpClientName, string uriString, int Timeout = 0)
        {
            services.AddHttpClient(httpClientName, c =>
            {
                c.Timeout=new TimeSpan(0, 0, Timeout>0 ? Timeout : ConfigCore.GetConfig<ApiClientKeyConfig>().DefalutHttpClientTimeout);
                c.BaseAddress = new Uri(uriString);
            });
            var types = assembly.GetTypes().Where(t => t.BaseType == (typeof(T)));
            foreach (var type in types)
            {
                services.AddSingleton(type);
            }
        }



        /// <summary>
        /// 加载调用api 需要的配置
        /// </summary>
        /// <param name="services"></param>
        /// <param name="Configuration"></param>
        public static void RegisterClientConfig(this IServiceCollection services, IConfiguration Configuration)
        {
            var CustomAppsettingsPath = Configuration.GetValue<string>("CustomAppsettingsPath");

            if (string.IsNullOrWhiteSpace(CustomAppsettingsPath))
            {
                throw new Exception("请配置 CustomAppsettingsPath 路径信息！");
            }
            CustomAppsettingsPath = Path.GetFullPath(CustomAppsettingsPath);
            if (!System.IO.File.Exists(CustomAppsettingsPath))
            {
                throw new Exception($"配置文件不存在!{CustomAppsettingsPath}");
            }
            var builder = new ConfigurationBuilder().AddJsonFile(CustomAppsettingsPath, false, true);
            var _configuration = builder.Build();
            var types = AssembliesExtensions.UserAssemblies.SelectMany(a => a.GetTypes().Where(t => t.IsInterface == false && t.GetInterfaces().Contains(typeof(BaseConfig)))).ToArray();
            foreach (var type in types)
            {
                var configuration = _configuration.GetSection(type.Name);
                var config = Activator.CreateInstance(type) as BaseConfig;
                configuration.Bind(config);
                ConfigCore.AddConfig(config);
                services.AddSingleton(type, config);
            }
        }

    }
}
